package com.bluefish.bltuan.service.impl;

import java.util.List;
import java.util.Observable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bluefish.bltuan.dao.EmailTemplateDao;
import com.bluefish.bltuan.module.mail.EmailPurpose;
import com.bluefish.bltuan.module.mail.EmailTemplate;
import com.bluefish.bltuan.observer.ApplicationObserver;
import com.bluefish.bltuan.service.EmailTemplateService;

@Service
@Transactional
public class EmailTemplateServiceImpl extends Observable implements EmailTemplateService {

    private EmailTemplateDao emailTemplateDao;

    @Autowired
    public EmailTemplateServiceImpl(ApplicationObserver applicationObserver) {
        addObserver(applicationObserver);
    }

    public void delete(EmailTemplate t) {
        this.emailTemplateDao.delete(t);
    }

    public EmailTemplate findById(Integer id) {
        return this.emailTemplateDao.findById(id);
    }

    public void save(EmailTemplate t) {
        this.emailTemplateDao.save(t);
        notifyObservers(t);
    }

    public void update(EmailTemplate t) {
        this.emailTemplateDao.update(t);
        notifyObservers(t);
    }

    public EmailTemplate findByPurpose(EmailPurpose purpose) {
        List<EmailTemplate> templates = this.emailTemplateDao.listByPurpose(purpose);
        return templates != null && templates.size() > 0 ? templates.get(0) : null;
    }

    public EmailTemplate getRegisterTemplate() {
        return findByPurpose(EmailPurpose.REGISTER);
    }

    public EmailTemplate getFindPasswordTemplate() {
        return findByPurpose(EmailPurpose.FIND_PASSWORD);
    }

    public EmailTemplate getSubscriberNotYetTemplate() {
        return findByPurpose(EmailPurpose.SUBSCRIBER_NOT_YET);
    }

    public EmailTemplate getSubscriberTemplate() {
        return findByPurpose(EmailPurpose.SUBSCRIBER);
    }

    public void saveOrUpdate(EmailTemplate template) {
        this.emailTemplateDao.saveOrUpdate(template);
        notifyObservers(template);
    }

    public void setEmailTemplateDao(EmailTemplateDao emailTemplateDao) {
        this.emailTemplateDao = emailTemplateDao;
    }
}
